package com.sun.util;

import jakarta.servlet.http.Part;

import java.io.File;

/**
 * @author SunRui
 * @description 图片上传
 * @date 2024/7/4 21:13
 */
public class ImageUtil {
    public static String saveImage(Part part, String filePath) {
        String imagePath = "";
        String contentType = part.getContentType();
        if (!(contentType == null || "".equals(contentType.trim()))) {
            imagePath = extractFileName(part);
            System.out.println("图片名称：" + imagePath);
            if (!imagePath.equals("")) {
                try {
                    part.write(filePath + File.separator + imagePath);
                    System.out.println("上传成功后的文件名是：" + imagePath + "，文件大小是：" + part.getSize() + "bytes!");
                } catch (Exception e) {
                    System.out.println("上传失败");
                }
            }
        }
        return imagePath;
    }

    private static String extractFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        String[] items = contentDisposition.split(";");
        for (String item : items) {
            if (item.trim().startsWith("filename")) {
                return item.substring(item.indexOf("=") + 2, item.length() - 1);
            }
        }
        return "";
    }
}
